export const parseDistrictTree = (tree) =>{
    let result = parseDfs(tree)
    result.children.unshift({
        value: -1,
        label: '无',
        children:[]
    })
    console.log(result)
    return result.children
}

const parseDfs = (node) => {
    let parsedNode = {
        value: 0,
        label: '',
        children: []
    }
    parsedNode.value = node.id
    parsedNode.label = node.data.name
    
    let childrenList = []
    for(let i = 0;i < node.children.length; i++){
        childrenList.push(parseDfs(node.children[i]))
    }

    parsedNode.children = childrenList
    return parsedNode
}

export const getAllDistrictsList = (tree) => {
    let list = []
    getAllDistrictsDfs(tree, list)
    list.forEach((item)=>{
        item.children = null
    })
    return list
}

const getAllDistrictsDfs = (node, list) => {
    if(node.data.type === 3)
        list.push(node)
    for(let i = 0;i < node.children.length; i++){
        getAllDistrictsDfs(node.children[i], list)
    }
}

export const districtTypeList = [
    {
        value: 1,
        label: '一级片区',
    },
    {
        value: 2,
        label: '二级片区',
    },
    {
        value: 3,
        label: '三级片区',
    },
]

export const getDistrictTypeName = (district) =>{

    for(let i = 0;i < districtTypeList.length; i++) {
        if(district.type === districtTypeList[i].value){
            return districtTypeList[i].label
        }
    }
    return '未知类型'
}

export const getDistrictFullName = (districtList, id) => {
    let rootNode = {
        value: -1,
        label: '',
        children: districtList
    }
    return getFullNameDfs(rootNode, id, '')
}

const getFullNameDfs = (node, id, tempName) => {

    console.log('正在搜索' + node.label)

    if(node.value === id){
        console.log('已找到'+ id)
        return node.label
    }

    for(let i = 0;i < node.children.length; i++){
        let tempResult = getFullNameDfs(node.children[i], id, tempName + node.label)
        if (tempResult !== null) {
            return tempName + node.label + tempResult
        }
    }
    return null
}

import {districtTreeQueryService} from '@/api/district.js'

//树状查询获取用户列表
export const getDistrictTree = async()=>{
    let result = await districtTreeQueryService(-1);
    let tree = result.data
    let parsedTree = parseDistrictTree(tree)
    return parsedTree
    
}
